package com.hugh.lagouservicecode.service.impl;

import com.hugh.lagouservicecode.dao.LagouAuthCodeDao;
import com.hugh.lagouservicecode.pojo.LagouAuthCode;
import com.hugh.lagouservicecode.service.LagouAuthCodeService;
import com.hugh.lagouservicecode.service.impl.entity.LagouAuthCodeEntity;
import com.hugh.lagouservicecode.util.CheckCodeResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: Hugh
 * @Date: 2020/7/19
 */
@Service
@Slf4j
public class LagouAuthCodeServiceImpl implements LagouAuthCodeService {

    @Autowired
    private LagouAuthCodeDao lagouAuthCodeDao;


    @Override
    public Boolean saveCode(LagouAuthCodeEntity request) {
        LagouAuthCode lagouAuthCode = LagouAuthCode.builder()
                .code(request.getCode())
                .email(request.getEmail())
                .createtime(LocalDateTime.now())
                .expiretime(request.getExpiretime())
                .build();
        lagouAuthCodeDao.save(lagouAuthCode);
        return Boolean.TRUE;
    }

    @Override
    public CheckCodeResult checkCode(String email, String code) {
        LagouAuthCode lagouAuthCode = LagouAuthCode.builder()
                .email(email)
                .code(code)
                .build();
        Example<LagouAuthCode> example = Example.of(lagouAuthCode);
        List<LagouAuthCode> all = lagouAuthCodeDao.findAll(example, Sort.by(Sort.Direction.DESC, "id"));
        if(CollectionUtils.isEmpty(all)){
            return CheckCodeResult.ERROR;
        }
        LagouAuthCode checkLagouAuthCode = all.get(0);
        if(LocalDateTime.now().compareTo(checkLagouAuthCode.getExpiretime()) > 0){
            return CheckCodeResult.TIMEOUT;
        }
        return CheckCodeResult.SUCCESS;
    }
}
